package com.telit.common.service;

import com.telit.common.exception.ForestBaseException;
import io.minio.*;
import io.minio.http.Method;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.io.InputStream;
import java.util.UUID;

/**
 * @Auther amy
 * @Describe minio的业务层
 * @ConditionalOnBean 当MinioClient存在的时候才会去加载MinioService类
 */
//@Service
@Slf4j
//@ConditionalOnBean(MinioClient.class)
//@ConditionalOnClass(MinioClient.class)
public class MinioService {

    @Autowired
    private MinioClient minioClient;

    @Value("${forest.minio.expireTime}")
    private String expireTime;

    @Value("${forest.minio.partSize}")
    private String partSize;

    public void setMinioClient(MinioClient minioClient) {
        this.minioClient = minioClient;
    }

    public void setExpireTime(String expireTime) {
        this.expireTime = expireTime;
    }

    public void setPartSize(String partSize) {
        this.partSize = partSize;
    }

    /**
     * 上传图片文件以及地址
     */
    public String upload(String fileName,InputStream in,long objectSize,String bucket, String filePrefixName,String contentType,String targetFileName) {
        // 获取新文件名称
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        if(StringUtils.isEmpty(targetFileName)){
            targetFileName = new UUID(RandomUtils.nextLong(), RandomUtils.nextLong()).toString().replace("-", "");
        }
        String newName = targetFileName + suffix;
        String objectName = StringUtils.EMPTY;
        try {
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucket).build());
            if (!found) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucket).build());
            }

            // 拼接objectName
            if (StringUtils.isNotBlank(filePrefixName)) {
                objectName = filePrefixName + "/" + newName;
            } else {
                objectName = newName;
            }
            // partSize=-1默认上传就是5M
            minioClient.putObject(PutObjectArgs.builder().bucket(bucket)
                                    .object(objectName).stream(in,objectSize,Long.valueOf(partSize))
                                    .contentType(StringUtils.isBlank(contentType)?"application/x-download":contentType)
                                    .build());
            in.close();
            return bucket + "/" + objectName;
        } catch (Exception e) {
            log.error("upload img is failed,exception:{}", e.getMessage());
            throw new ForestBaseException(e.getMessage());
        }
    }

    /**
     * 预览图片
     * @return
     */
    public String previewImg(String bucket,String objectName) {
        try {
            GetPresignedObjectUrlArgs getPresignedObjectUrlArgs = GetPresignedObjectUrlArgs.builder().bucket(bucket).object(objectName)
                                                                    .expiry(Integer.valueOf(expireTime))
                                                                    .method(Method.GET).build();
            return minioClient.getPresignedObjectUrl(getPresignedObjectUrlArgs);
        } catch (Exception e) {
            log.error("minio preview image is failed,exception:{}", e.getMessage());
            throw new ForestBaseException(e.getMessage());
        }
    }

    /**
     * 删除文件
     * @return
     */
    public void removeMinio(String bucketName, String objectName) {
        try {
            minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(objectName).build());
        } catch (Exception e) {
            log.error("minio remove file is failed,exception:{}",e.getMessage());
            throw new ForestBaseException(e.getMessage());
        }
    }

    /**
     * 下载文件
     * @param bucketName 桶名称
     * @param objectName
     */
    public InputStream download(String bucketName, String objectName){
        try {
            InputStream inputStream =  minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(objectName).build());
            return inputStream;
        } catch (Exception e) {
            log.error("minio download file is failed,exception:{}",e.getMessage());
            throw new ForestBaseException(e.getMessage());
        }
    }

}
